// router/guard.ts
import { RouteLocationNormalized, Router } from 'vue-router';
import { to as tos } from 'await-to-js';
import NProgress from 'nprogress';
import { getToken } from '@/utils/auth';
import { isRelogin } from '@/utils/request';
import useUserStore from '@/store/modules/user';
import useSettingsStore from '@/store/modules/settings';
import { message as AntMessage } from "ant-design-vue";
import { useGlobalLoading } from '@/utils/loading';

NProgress.configure({ showSpinner: false });

// 白名单路由
const whiteList = [
  '/login',
  '/register',
  '/social',
  '/social/hot',
  '/social/detail',
  '/angling',
  '/angling/detail',
  '/shopping',
  '/shopping/detail',
  '/fishKnowledge',
  '/chat'
];

export default function(router: Router) {
  const { setLoading } = useGlobalLoading();

  // 路由守卫
  router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: any) => {
    NProgress.start();
    setLoading(true); // 开始路由切换时显示loading
    if (getToken()) {
      // 如果存在 token
      to.meta.title && useSettingsStore().setTitle(to.meta.title);

      if (to.path === '/login') {
        next({ path: '/' });
        NProgress.done();
      } else {
        // 获取用户登录信息
        if (!useUserStore().userId) {
          isRelogin.show = true;
          const [err] = await tos(useUserStore().getInfo());
          if (err) {
            await useUserStore().logout();
            AntMessage.error(err.message);
            next({ path: '/' });
          } else {
            isRelogin.show = false;
            // @ts-ignore
            next({ path: to.path, replace: true, params: to.params, query: to.query, hash: to.hash, name: to.name as string });
          }
        } else {
          next();
        }
      }
    } else {
      
      if (whiteList.indexOf(to.path as string) !== -1) {
        // 在免登录白名单，直接进入
        next();
      } else {
        const redirect = encodeURIComponent(to.fullPath || '/');
        next(`/login?redirect=${redirect}`);
        NProgress.done();
      }
    }
  });

  // 路由跳转后
  router.afterEach(() => {
    NProgress.done();
    // 添加一个小延迟，确保页面内容加载完成
    setTimeout(() => {
      setLoading(false);
    }, 300);
  });
}
